<template>
  <div class="search-container">
    <!-- 顶部搜索栏 -->
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        background="#3296fa"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result
      v-if="isResultShow"
      :search-text="searchText"
    ></search-result>

    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    ></search-suggestion>

    <!-- 搜索历史 -->
    <search-history
      v-else
      :search-historys="searchHistorys"
      @clear-search-history="searchHistorys = []"
      @search="onSearch"
    ></search-history>
  </div>
</template>

<script>
// 加载子组件模块
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
// 加载获取本地存储请求的方法
import { setItem, getItem } from '@/utils/storage'

export default {
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  name: 'SearchIndex',
  watch: {
    searchHistorys(value) {
      // 把搜索记录存储到本地,便于持久化
      setItem('TOUTIAO_SEARCH_HISTORYS', value)
    }
  },
  data() {
    return {
      searchText: '',
      isResultShow: false, //搜索结果的展示
      searchHistorys: getItem('TOUTIAO_SEARCH_HISTORYS') || [] //有本地就用,没有就空数组
    }
  },
  methods: {
    // 触发搜索事件
    onSearch(value) {
      // 1.更新搜索框内容
      this.searchText = value
      // 2.去除重复搜索内容
      const index = this.searchHistorys.indexOf(value)
      // 如果搜索历史里面已经存在
      if (index != -1) {
        // 移除重复内容
        this.searchHistorys.splice(index, 1)
      }
      // 3.去重后追加到最前面
      this.searchHistorys.unshift(value)
      // 4.渲染搜索结果
      this.isResultShow = true
    },
    // 点击取消返回首页
    onCancel() {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  .van-search__action {
    color: #fff;
  }
}
</style>